<?php 
namespace app\index\controller;

use think\Request;
use app\common\model\Article as ArticleModel;
use app\common\model\Badge;
use app\common\model\ArticleEval;

class Article extends Base
{
	private $article;
	
	public function initialize()
	{
		parent::initialize();
		$this->article = new Articles();
	}
	public function index(Request $request)
	{
		$coms = new Articles();
		//获取客户端传递的数据
		$id = $request->param('id');
		//获取文章详情
		$article = ArticleModel::get($id);
		$article->badge_name = Badge::get($article->badge)->name;
		$article_eval = $coms->getArticleEval($id);
		$eval_num = ArticleEval::where(['article_id' => $id])->count();
		//获取所有评论
		$evals = ArticleEval::where(['article_id' => $id])->field('sender,content')->select();
		//渲染模板
		$article_title = $article->title;
		$this->assign('eval_num',$eval_num);
		$this->assign('evals',json_encode($evals->toArray()));
		$this->assign('article_eval',json_encode($article_eval));
		$this->assign('article_title',$article_title);
		$this->assign('article',json_encode($article->toArray()));
		return view();
	}
	/**
	 * 获取更多评论
	 * @param Request $request
	 */
	public function getMoreEval(Request $request)
	{
		$article_id = $request -> param('id');
		$article_eval = $this->article->getArticleEval($article_id);
		return $this->success($article_eval);
	}
	/**
	 * 评论文章
	 * @param Request $request
	 * @throws Exception
	 */
	public function toEval(Request $request)
	{
		//获取客户端传递的数据
		$data = $request -> param('');
		try {
			if(!$data['sender']) throw new Exception('请输入昵称');
			if(!$data['sender_email']) throw new Exception('请输入邮箱');
			if(!$data['sender_web']) throw new Exception('请输入网址');
			if(!$data['content']) throw new Exception('请输入评论内容');
			//添加评论
			$data['create_time'] = time();
			ArticleEval::create($data);
		} catch (Exception $e) {
			return $this->error($e->getMessage());
		}
		return $this->success('评论成功');
	}
}